<?php
namespace app\interfaces\controller;

use app\interfaces\model\Feedback as FeedbackModel;
use app\interfaces\model\FeedbackType as FeedbackTypeModel;
use think\Request;
use think\Cache;
use think\Exception;

class Feedback
{

    /*
     * 用户端 - 反馈分类列表
     */
    public function feedback_list()
    {

        $model = new FeedbackTypeModel();

        $list = $model->where(['status' => '1'])->field('title')->order(['sort' => 'desc'])->select();

        return ['code' => 200, 'message' => '成功', 'data' => $list];

    }

    /*
     * 用户端 - 反馈提交
     * @param  string $type         分类
     * @param  string $content      反馈内容
     * @param  string $contact      联系方式
     */
    public function feedback_create()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['content'])) throw new Exception('not Empty');

        $data['ip'] = $this->getIP();


        if (!empty(Cache::get('ip_verify_' . ip2long($data['ip'])))) {
            return ['code' => 401, 'message' => '5分钟内只能反馈一次'];
        }

        Cache::set('ip_verify_' . ip2long($data['ip']), $data['ip'], 300); // 短信请求有效期

        // 展示数据
        $model = new FeedbackModel();

        $result = $model->allowField(true)->save($data);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    // 获取IP
    protected function GetIP()
    {
        static $ip = NULL;
        if ($ip !== NULL) return $ip;

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        //IP地址合法验证
        $ip = (false !== ip2long($ip)) ? $ip : '222.171.225.188';
        return $ip;
    }

}
